<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑抽取任务' : '添加抽取任务' }}</span>
      </div>

      <el-form 
        ref="dataForm" 
        :model="form" 
        :rules="rules" 
        label-width="120px" 
        class="demo-form"
        size="small"
      >
        <el-form-item label="任务名称" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入任务名称"
            style="width: 400px"
          />
        </el-form-item>

        <el-form-item label="全宗号" prop="qzh">
          <el-input 
            v-model="form.qzh" 
            placeholder="请输入全宗号"
            style="width: 400px"
          />
        </el-form-item>

        <el-form-item label="Ollama地址" prop="ollama_url">
          <el-input 
            v-model="form.ollama_url" 
            placeholder="请输入Ollama服务地址"
            style="width: 400px"
          >
            <template slot="prepend">http://</template>
          </el-input>
          <div class="input-help">例如：127.0.0.1:8080</div>
        </el-form-item>

        <el-form-item label="数据限制" prop="limit">
          <el-input-number 
            v-model="form.limit" 
            :min="0"
            :step="10"
            controls-position="right"
            style="width: 200px"
          />
          <div class="input-help">0表示不限制数据量</div>
        </el-form-item>

        <el-form-item label="启用状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">未启动</el-radio>
            <el-radio :label="1">已启动</el-radio>
            <el-radio :label="2">运行中</el-radio>
            <el-radio :label="3">已暂停</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="运行配置" v-if="form.status !== 0">
          <el-card class="config-card">
            <el-form-item label="并发数" prop="concurrent">
              <el-input-number 
                v-model="form.concurrent" 
                :min="1"
                :max="10"
                controls-position="right"
                style="width: 150px"
              />
              <div class="input-help">设置任务并发处理数量，建议1-10之间</div>
            </el-form-item>

            <el-form-item label="重试次数" prop="retry_times">
              <el-input-number 
                v-model="form.retry_times" 
                :min="0"
                :max="3"
                controls-position="right"
                style="width: 150px"
              />
              <div class="input-help">失败后重试次数，0表示不重试</div>
            </el-form-item>

            <el-form-item label="超时时间" prop="timeout">
              <el-input-number 
                v-model="form.timeout" 
                :min="30"
                :step="30"
                controls-position="right"
                style="width: 150px"
              />
              <div class="input-help">单个任务超时时间（秒）</div>
            </el-form-item>
          </el-card>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { api } from '@/api/template'

export default {
  name: 'ExtractionTaskManagementSave',
  data() {
    return {
      isEdit: false,
      form: {
        id: undefined,
        name: '',
        qzh: '',
        ollama_url: '',
        limit: 0,
        status: 0,
        concurrent: 1,
        retry_times: 0,
        timeout: 300
      },
      rules: {
        name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        qzh: [
          { required: true, message: '请输入全宗号', trigger: 'blur' }
        ],
        ollama_url: [
          { required: true, message: '请输入Ollama服务地址', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9\-\.]+\:[0-9]+$/, message: '请输入正确的服务地址格式', trigger: 'blur' }
        ],
        concurrent: [
          { required: true, message: '请设置并发数', trigger: 'blur' }
        ],
        timeout: [
          { required: true, message: '请设置超时时间', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.$route.query.id) {
      this.isEdit = true
      this.getDetail()
    }
  },
  methods: {
    async getDetail() {
      try {
        const response = await api('getObtainDetail', { id: this.$route.query.id })
        if (response.code === 200) {
          // 处理ollama_url，移除http://前缀
          let ollamaUrl = response.data.ollama_url || ''
          ollamaUrl = ollamaUrl.replace(/^http:\/\//, '')
          
          this.form = {
            ...response.data,
            ollama_url: ollamaUrl
          }
        }
      } catch (error) {
        console.error('获取详情失败:', error)
        this.$message.error('获取任务详情失败')
      }
    },
    submitForm() {
      this.$refs.dataForm.validate(async (valid) => {
        if (valid) {
          try {
            // 添加http://前缀
            const submitData = {
              ...this.form,
              ollama_url: 'http://' + this.form.ollama_url.replace(/^http:\/\//, '')
            }
            
            const action = this.isEdit ? 'updateObtain' : 'addObtain'
            const response = await api(action, submitData)
            
            if (response.code === 200) {
              this.$notify({
                title: '成功',
                message: this.isEdit ? '修改成功' : '添加成功',
                type: 'success',
                duration: 2000
              })
              this.goBack()
            }
          } catch (error) {
            console.error('保存失败:', error)
            this.$message.error('保存失败')
          }
        }
      })
    },
    goBack() {
      this.$router.push('/template/extractiontaskmanagement')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .box-card {
    margin-bottom: 20px;
    
    .clearfix {
      font-size: 16px;
      font-weight: 500;
    }
  }
  
  .demo-form {
    width: 100%;
    padding: 20px;
    
    .input-help {
      font-size: 12px;
      color: #909399;
      line-height: 1.2;
      padding-top: 4px;
    }

    .config-card {
      width: 600px;
      margin-top: 10px;
      
      ::v-deep .el-card__body {
        padding: 20px 20px 0;
      }
    }
  }
}
</style>
